package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Dee
 * @date 2023/10/31
 * <p>Description: 多线程下的
 */
@Slf4j
public class DeeMultiThreadServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
        Selector sel = Selector.open();
        ssc.register(sel, SelectionKey.OP_ACCEPT, null);
        // 创建worker
        Worker worker = new Worker("worker-1");
        while (true) {
            sel.select();
            Iterator<SelectionKey> iter = sel.selectedKeys().iterator();
            if (iter.hasNext()) {
                SelectionKey sk = iter.next();
                iter.remove();
                if (sk.isAcceptable()) {
                    log.info("客户端已连接... {}",  worker.name);
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    // 绑定worker的selector
                    worker.register(); // 初始化
                    sc.register(worker.selector, SelectionKey.OP_READ, null);
                }
            }

        }
    }
    // 多线程
    static class Worker implements Runnable {
        // 当前线程
        private Thread thread;
        // 选择器
        private Selector selector;
        private String name;
        private volatile boolean start = false;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }
        // 初始化
        public void register() throws IOException {
            if (!start) {
                selector = Selector.open();
                thread = new Thread(this);
                thread.start();
                start = true;
            }
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    if (iter.hasNext()) {
                        SelectionKey sk = iter.next();
                        iter.remove();
                        if (sk.isReadable()) {
                            SocketChannel sc = (SocketChannel) sk.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            sc.read(buffer);
                            buffer.flip();
                            System.out.println(StandardCharsets.UTF_8.decode(buffer));
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
